/**
 * @Author yinyunqi
 * @date 2017年12月30日
 * @Content 
 */
package com.yongqi.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.yongqi.model.Family;
import com.yongqi.service.FamilyService;

public class MyShiroRealm extends AuthorizingRealm{
    @Autowired
    FamilyService familyService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	// TODO Auto-generated method stub
	return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	System.out.println("doGetAuthenticationInfo验证");
	// 通过表单获得的账户名
	String familyaccount = (String) token.getPrincipal();
	System.out.println(familyaccount);
	// select password from member where account=#{account}
	// 获取一个Member类的member
	Family family = familyService.getFamilyByAccount(familyaccount);
	if (!StringUtils.isEmpty(family)) {
	    if (family.getFamilypassword() != null) {

		// 验证交给shiro
		// 三个参数为Member对象，从数据库获取的密码，当前Realm名称
		// 登录账户account相当于username，必然是相同的
		// 因为是从表单获得的account，然后拿来查询，比较的是从数据库获取得password和token中获得的password
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(family,
			family.getFamilypassword(), ByteSource.Util.bytes(family.getFamilyaccount()), // 加盐，用户account
			getName());
		return simpleAuthenticationInfo;
	    }else {
		throw new AuthenticationException();
	    }
	}
	return null;
    }

}
